﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Channels;
using System.ServiceModel;
using ajayumi.develop.win32.Transport.WCF.Services;

namespace ajayumi.develop.win32.Transport.WCF.ServiceImpls
{
    /// <summary>
    /// TransportFileBase.cs 文件传输基类
    /// Author   : 黄乙冬
    /// Date     : 2011-11-09
    /// </summary>
    public abstract class TransportFileBase
    {
        #region Variables

        protected readonly object m_LockObj = null;

        #endregion

        #region Properties

        /// <summary>
        /// 获取服务器下行的缓冲区大小的委托
        /// </summary>
        public Func<int> GetBufferSize { get; set; }

        /// <summary>
        /// 获取客户端上传文件的保持目录的委托
        /// </summary>
        public Func<string> GetSaveDirectory { get; set; }

        #endregion

        public TransportFileBase()
        {
            this.m_LockObj = new object();
        }

        #region Events
        public event EventHandler<TransReadyEventArgs> TransReady;
        public event EventHandler<TransCompletedEventArgs> TransCompleted;
        public event EventHandler<TransProgressChangedEventArgs> TransProgressChanged;


        #region OnTransReady
        /// <summary>
        /// Triggers the TransReady event.
        /// </summary>
        public virtual void OnTransReady(TransReadyEventArgs e)
        {
            if (TransReady != null)
                TransReady(this, e);
        }
        #endregion
        #region OnTransCompleted
        /// <summary>
        /// Triggers the TransCompleted event.
        /// </summary>
        public virtual void OnTransCompleted(TransCompletedEventArgs e)
        {
            if (TransCompleted != null)
                TransCompleted(this, e);
        }
        #endregion
        #region OnTransProgressChanged
        /// <summary>
        /// Triggers the TransProgressChanged event.
        /// </summary>
        public virtual void OnTransProgressChanged(TransProgressChangedEventArgs e)
        {
            if (TransProgressChanged != null)
                TransProgressChanged(this, e);
        }
        #endregion

        #endregion

        /// <summary>
        /// 获取客户端IP
        /// </summary>
        /// <returns></returns>
        protected string GetClientIp()
        {
            MessageProperties mp = OperationContext.Current.IncomingMessageProperties;
            RemoteEndpointMessageProperty rem = mp[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
            if (rem == null)
            { return string.Empty; }
            else
            { return rem.Address; }
        }
    }
}
